import React from 'react';
import { SafeAreaView, Alert, View, ActivityIndicator } from 'react-native';
import { WebView } from 'react-native-webview';

interface RouteParams {
    params: {
        html: string;
    };
}

const AlipayWebView = ({ route, navigation }: { route: RouteParams; navigation: any }) => {
    const { html } = route.params;
  
    // 处理WebView URL变化
    const handleNavigationStateChange = (navState: any) => {
        console.log('WebView URL 变化:', navState.url);
        
        // 如果URL包含支付成功的标识
        if (navState.url && (
            navState.url.includes('payment_success') ||
            navState.url.includes('alipay.trade.wap.pay.return') ||
            navState.url.includes('success=true')
        )) {
            // 显示支付成功
            Alert.alert(
                '支付成功', 
                '您已成功开通AI医疗健康会员服务!', 
                [{ 
                    text: '确定', 
                    onPress: () => navigation.navigate('MainTabs')
                }]
            );
            return false; // 阻止WebView加载这个URL
        }
        
        return true; // 允许其他URL正常加载
    };

    // 处理WebView加载错误
    const handleError = (syntheticEvent: any) => {
        const { nativeEvent } = syntheticEvent;
        console.error('WebView错误:', JSON.stringify(nativeEvent));
        
        Alert.alert(
            '支付遇到问题',
            '请稍后再试或联系客服',
            [
                {
                    text: '返回',
                    onPress: () => navigation.goBack()
                }
            ]
        );
    };

    // 注入JavaScript自动提交表单
    const injectedJavaScript = `
        (function() {
            try {
                console.log('WebView加载完成，检查表单');
                
                // 自动提交表单
                if (document.forms.length > 0) {
                    console.log('找到支付表单，自动提交');
                    document.forms[0].submit();
                } else {
                    console.log('未找到支付表单');
                }
            } catch(e) {
                console.error('表单处理错误:', e);
            }
            true;
        })();
    `;

    return (
        <SafeAreaView style={{ flex: 1 }}>
            <WebView 
                source={{ html }} 
                onNavigationStateChange={handleNavigationStateChange}
                javaScriptEnabled={true}
                domStorageEnabled={true}
                originWhitelist={['*']}
                mixedContentMode="always"
                allowFileAccess={true}
                injectedJavaScript={injectedJavaScript}
                onError={handleError}
                onHttpError={(e) => console.log('HTTP错误:', JSON.stringify(e.nativeEvent))}
                startInLoadingState={true}
                renderLoading={() => (
                    <View style={{
                        flex: 1,
                        justifyContent: 'center',
                        alignItems: 'center',
                        backgroundColor: '#f8f8f8'
                    }}>
                        <ActivityIndicator size="large" color="#007AFF" />
                    </View>
                )}
            />
        </SafeAreaView>
    );
};

export default AlipayWebView;